//
//  lognViewController.m
//  dongfengTest
//
//  Created by wxt on 2021/3/16.
//

#import "LognViewController.h"
#import "PassWordViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "FaceIDViewController.h"
#import "LZActionSheetView.h"
#import "BiomerLognViewController.h"
#import "LoginPassWordViewController.h"
#import "PhonePickView.h"

#import "LoginPassWordViewController.h"
#import "CodeViewController.h"
#import "ViewController.h"
@interface LognViewController ()<pickerDelegate,UITextFieldDelegate,NoNetworkViewDelegate>
@property(nonatomic,strong)TKLtextFiled * passWordF;
@property(nonatomic,strong)TKLlable * messageLab;
@property(nonatomic,strong)UIView * messageView;
//@property (retain,nonatomic) LAContext *faceIDContext;
@property (assign,nonatomic) NSInteger BiometryTypeNumber;
@property (strong,nonatomic) NSString * BiometryTypeStr;
@property (nonatomic, strong) UIView *headView;
@property(nonatomic,strong)NSMutableArray * userNameArr;
@property(nonatomic,strong)UIButton * changeBtn;
@property(nonatomic,strong)NSString * userPhone;
@property(nonatomic,strong)MBProgressHUD *hud;
@end

@implementation LognViewController
-(NSMutableArray *)userNameArr{
    
    if (!_userNameArr) {
        _userNameArr = [NSMutableArray array];
    }
    return _userNameArr;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    [self  loadUIView];
    
    //注册通知 证书下载成功登录
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cerCallBack:) name:@"downCerSuccess" object:nil];
    //token过期
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenNoTime:) name:@"tokenNotime" object:nil];
    //加载数据库
    [self selectDataList];
    //是否支持生物识别
    [  self isSupportBiometrics];
 
    // Do any additional setup after loading the view.
}
-(void)tokenNoTime:(NSNotification *)sender{
    [MBProgressHUD showError:@"token过期，请重新登录" toView:self.view];
}
-(void)cerCallBack:(NSNotification*)sender{

    [self getUserPhoneNumber];
    
}

-(void)loadUIView{
    
    
    TKLlable * lognLab = [TKLlable labelWithFrame:CGRectMake(30, 100, 50, 30) text:@"登录" textColor:JhColor(51, 51, 51) font:Font_6(24) textAlignment:Textleft backgroundColor:Ccolor];
    
    lognLab.font = [UIFont fontWithName:@"Arial-BoldMT" size:24];
    
    [self.view addSubview:lognLab];
    

    
    //提示信息
    self.messageLab = [TKLlable labelWithFrame:CGRectMake(30, CGRectGetMaxY(lognLab.frame)+30, kWidth-60, 14) text:@"" textColor:[UIColor redColor] font:Font_6(12) textAlignment:Textleft backgroundColor:Ccolor];
    self.messageLab.hidden = YES;
    [self.view addSubview:self.messageLab];
    
    
    
    self.passWordF = [TKLtextFiled FiledWithFrame:CGRectMake(30, CGRectGetMaxY(lognLab.frame)+50,kWidth-120 , 20) text:@"请选择登录账号" textColor:JhColor(51, 51, 51) font:Font_6(14) textAlignment:Textleft backgroundColor:Ccolor];

    
    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
    
    self.passWordF.text = [stand objectForKey:@"userName"];
    self.passWordF.delegate = self;
    [self.view addSubview:self.passWordF];
    

    self.changeBtn = [UIButton createBtnFrame:CGRectMake(kWidth-90, CGRectGetMaxY(lognLab.frame)+50, 30, 20) title:@"更换" bgImageName:@"" action:^(UIButton *button) {
        [self.view endEditing:YES];
        [self loadPickView];
        
        
    }];
    [self.changeBtn setTitleColor:JhColor(204, 204, 204) forState:UIControlStateNormal];
    [self.view addSubview:self.changeBtn];

    
    
    
    self.messageView = [[UIView alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(self.passWordF.frame)+10, kWidth-60, 1)];
    self.messageView.backgroundColor = JhColor(153, 153, 153);
    [self.view addSubview:self.messageView];
    
    //next
    UIButton * nextBtn = [UIButton createBtnFrame:CGRectMake(30, CGRectGetMaxY(self.messageView.frame)+20, kWidth-60, 44) title:@"下一步" bgImageName:@"" action:^(UIButton *button) {
        

        
        if (self.passWordF.text.length >0) {
            //查询账号是否激活
            
            [self getUserPhoneNumber];
        }else{
            [MBProgressHUD showMessage:@"请输入资金账号" toView:self.view];
        }
        
     
        


    }];
    //    nextBtn
    nextBtn.backgroundColor = JhColor(21, 126, 251);
    nextBtn.layer.masksToBounds = YES;
    nextBtn.layer.cornerRadius = 5;
    [self.view addSubview:nextBtn];
    
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
  
    if (textField == self.passWordF) {
      
        self.messageLab.hidden = YES;
        self.messageView.backgroundColor = JhColor(153, 153, 153);
    }
  
    
}
-(void)isSupportBiometrics{
    
    
    
    self.BiometryTypeNumber = [BiomerTool isSupportBiometrics];
    
    //    NSLog(@"%ld",[biomerTool isSupportBiometrics]);
    if (self.BiometryTypeNumber == 1) {
        self.BiometryTypeStr = @"指纹";;
    }else if(self.BiometryTypeNumber == 2){
        
        self.BiometryTypeStr = @"面部";
    }else{
        self.BiometryTypeStr = @"生物";
    }
    
    
    
    
}


-(void)getUserPhoneNumber{
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
      self.hud.labelText = NSLocalizedString(@"请稍等", @"HUD loading title");
    
    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kVerUserNumber_Activity_Api WithString:self.passWordF.text WithReturnValeuBlock:^(id  _Nonnull returnValue) {
          NSLog(@"%@",returnValue)  ;
        
        if ([returnValue[@"code"] intValue] == 200) {
            ;
            NSDictionary * mindic = returnValue[@"data"];
            self.userPhone = mindic[@"mobile"];
            if ([mindic[@"isMobile"] intValue] == 3) {
                //为3  激活  判断是否有证书
                NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
                //本机是否开启生物登录
                NSArray * deviceArr = mindic[@"muDevices"];
                if ([deviceArr isKindOfClass:[NSNull class]] || [deviceArr isEqual:[NSNull null]]) {
                  
                    //为开启
                    [stand setObject:@"0" forKey:@"bio"];
                }else{
                    [stand setObject:@"0" forKey:@"bio"];
                    [deviceArr enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                            if ([obj[@"deviceId"] isEqualToString:[IMSecurity getDeviceIdentifier]]&& [obj[@"fpSwitch"]intValue]==1) {
                               
                                [stand setObject:@"1" forKey:@"bio"];
                            }else{
                               
                               
                            }
                        }];
                  
                    
                    
                    
                }
                
                
                if (self.userPhone.length == 11) {
                    [self hasCerWithUserName];
                }else{
                    [MBProgressHUD showMessage:[NSString stringWithFormat:@"账户关联手机号:%@错误",self.userPhone] toView:self.view];
                }
                
           
                
                
                
            }else{
                self.hud.hidden = YES;
                self.messageLab.text = @"资金账号未激活,请输入正确的资金账号";
                self.messageLab.hidden = NO;
                self.messageView.backgroundColor = JhColor(239, 45, 47);
            }
            
            
            
            
        }else if([returnValue[@"code"] intValue] == 999){
            self.hud.hidden = YES;
            self.messageLab.text = @"请输入正确的资金账号";
            self.messageLab.hidden = NO;
            self.messageView.backgroundColor = JhColor(239, 45, 47);
        }
        
        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
            self.hud.hidden = YES;
        } WithFailureBlock:^{
            self.hud.hidden = YES;
        }];
  
}
-(void)selectDataList{
    
    FMDatabase *database =  [DataBaseTool openDataBase];
    
    NSString *selectSql = [NSString stringWithFormat:@"select * from user "];
    FMResultSet *resultSet = [database executeQuery:selectSql];
    while ([resultSet next]) {
        
        NSString *name = [resultSet stringForColumn:@"userName"];
      
        [self.userNameArr addObject:name];
    }
    [database close];
  
    if (self.userNameArr.count > 1) {
        //        self.changeBtn.hidden = NO;
    }else{
        //        self.changeBtn.hidden = YES;
    }
}
-(void)loadPickView{
    
    PhonePickView *pView = [[PhonePickView alloc ] initWithFrame:CGRectMake(0, kHeight-200, kWidth, 200) arr:self.userNameArr ];
    pView.delegate = self;
    
    
}
-(void)selectIndex:(NSInteger)index{
    self.passWordF.text = self.userNameArr[index];
    
}
-(void)hasCerWithUserName{
    
    IMUser *user = [IMUser userWithUserName:self.passWordF.text];
    self.hud.hidden = YES;
    if (user == nil) {

        
        
        
        ViewController * viewVC = [[ViewController alloc]init];

        viewVC.userName = self.passWordF.text;
        [UIApplication sharedApplication].keyWindow.rootViewController = viewVC;
        
        
    }else{
        
        if (![IMCert hasCertWithUsername:user.username]) {
            CodeViewController * codeVC =[[CodeViewController alloc]init];
            codeVC.userName  = self.passWordF.text;
         
                codeVC.pushPath = @"cer";
           
            codeVC.phoneNumberStr = self.userPhone;
            codeVC.modalPresentationStyle = 0;
            [self presentViewController:codeVC animated:YES completion:nil];
            
        }else{
            
  
            
            
           [ user.cert getCertStateWithCompleteBlock:^(int resultCode, NSDictionary *dictState) {
               NSLog(@"%@",dictState);
                if (resultCode == IM_ER_SUCCESS) {

                  //证书状态
                    if ([dictState[@"isexpired"] intValue] == 0) {
                        //不过期
                      //密码登录还是生物识别
                        NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
                        
                        if ([[stand objectForKey:@"bio"] isEqualToString:@"1"]) {
                            
                            //判断是够开启生物权限
                            if (self.BiometryTypeNumber == 0) {
                                LoginPassWordViewController * lognVC = [[LoginPassWordViewController alloc]init];
                                 lognVC.modalPresentationStyle = 0;
                                  lognVC.userPhone = self.userPhone;
                                  lognVC.cerDN =   [user.cert getCertInfoWithItem:CertItemTypeDN];
                                 lognVC.userName = self.passWordF.text;
                                  [self presentViewController:lognVC animated:YES completion:nil];
                            }else{
                                BiomerLognViewController * biomVC = [[BiomerLognViewController alloc]init];
                                 biomVC.modalPresentationStyle = 0;
                                biomVC.cerDn=   [user.cert getCertInfoWithItem:CertItemTypeDN];
//                                   NSLog(@"%@",biomVC.cerDn);
                                 biomVC.userName = self.passWordF.text;
                                 biomVC.BiometryTypeStr = self.BiometryTypeStr;
                                 biomVC.BiometryTypeNumber = self.BiometryTypeNumber;
                                 [self presentViewController:biomVC animated:YES completion:nil];
                            }
                            
                        
                        }else{
                          LoginPassWordViewController * lognVC = [[LoginPassWordViewController alloc]init];
                           lognVC.modalPresentationStyle = 0;
                            lognVC.userPhone = self.userPhone;
                            lognVC.cerDN =   [user.cert getCertInfoWithItem:CertItemTypeDN];
                           lognVC.userName = self.passWordF.text;
                            [self presentViewController:lognVC animated:YES completion:nil];
                        }
                      
                      
                       
  
                    }else{
                        //过期
//                        [MBProgressHUD showError:@"证书过期" toView:self.view];
                        CodeViewController * codeVC =[[CodeViewController alloc]init];
                        codeVC.phoneNumberStr = self.userPhone;
                        codeVC.pushPath = @"cer";
                        codeVC.userName  = self.passWordF.text;
//                        mobVC.pushPath = @"newUser";
                        codeVC.modalPresentationStyle = 0;
                        [self presentViewController:codeVC animated:YES completion:nil];
                    }
                    
                    
                
                }else{
                    IMUser * user = [IMUser userWithUserName:self.passWordF.text];
                    [user.cert deleteCert];
                    CodeViewController * codeVC =[[CodeViewController alloc]init];
                    codeVC.phoneNumberStr = self.userPhone;
                    codeVC.pushPath = @"cer";
                    codeVC.userName  = self.passWordF.text;
                    codeVC.modalPresentationStyle = 0;
                    [self presentViewController:codeVC animated:YES completion:nil];
//                    [MBProgressHUD showError:[NSString stringWithFormat:@"获取证书状态失败:%d",resultCode] toView:self.view];
//                    NSLog(@"获取证书状态失败:%d,%@",resultCode,dictState);
                }
            }];
        }
        
        
    }
    

}

-(void)queryOpenBiorm{
//    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
//    NSError *keychainError = [QiKeychainItem queryKeychainWithService:QikeychainService account: @"userUUID"];
//    
//    if (keychainError.code ==errSecSuccess) {
//        [NetRequestClass NetRequestPOSTWithRequestURL:kUser_UserAndDevice_Api   WithParameter:@{@"uno":self.passWordF.text,@"deviceId":[keychainError.userInfo valueForKey:NSLocalizedDescriptionKey] } WithReturnValeuBlock:^(id  _Nonnull returnValue) {
//              NSLog(@"%@",returnValue) ;
//            self.hud.hidden = YES;
//            if ([returnValue[@"code"] intValue] == 200) {
//  
//                NSDictionary * mindic =[TKLTools getValueFromDic:returnValue withKey:@"data"];
//                
//                if ([mindic isKindOfClass:[NSNull class]] || [mindic isEqual:[NSNull null]]) {
//                    [stand setObject:@"0" forKey:@"bio"];
//                    LoginPassWordViewController * lognVC = [[LoginPassWordViewController alloc]init];
//                    lognVC.modalPresentationStyle = 0;
//                  
//                    lognVC.userName = self.passWordF.text;
//                    [self presentViewController:lognVC animated:YES completion:nil];
//                }else{
//                    
//                    NSString  * userDeviceStatus = [TKLTools getValueFromDic:mindic withKey:@"useStatus"];
//                    
//                    if ([userDeviceStatus intValue] ==0) {
//                        //没有开启;
//                        [stand setObject:@"0" forKey:@"bio"];
//                        LoginPassWordViewController * lognVC = [[LoginPassWordViewController alloc]init];
//                        lognVC.modalPresentationStyle = 0;
//                     
//                        lognVC.userName = self.passWordF.text;
//                        [self presentViewController:lognVC animated:YES completion:nil];
//                    }else{
//                        //开启
//                        [stand setObject:@"1" forKey:@"bio"];
//                        BiomerLognViewController * biomVC = [[BiomerLognViewController alloc]init];
//                        biomVC.modalPresentationStyle = 0;
//                      
//                        biomVC.userName = self.passWordF.text;
//                        biomVC.BiometryTypeStr = self.BiometryTypeStr;
//                        biomVC.BiometryTypeNumber = self.BiometryTypeNumber;
//                        [self presentViewController:biomVC animated:YES completion:nil];
//                    }
//                }
//
//              
//            }
//            
//            
//            } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
//                self.hud.hidden = YES;
//            } WithFailureBlock:^{
//                self.hud.hidden = YES;
//            }];
//
//    }else{
//        self.hud.hidden = YES;
//        [stand setObject:@"0" forKey:@"bio"];
//        LoginPassWordViewController * lognVC = [[LoginPassWordViewController alloc]init];
//        lognVC.modalPresentationStyle = 0;
//        lognVC.userName = self.passWordF.text;
//        [self presentViewController:lognVC animated:YES completion:nil];
//    }
//    
//    
    
    
 
  
}

//- (LAContext *)faceIDContext{
//    if (!_faceIDContext) {
//        _faceIDContext = [[LAContext alloc] init];
//    }
//    return _faceIDContext;
//}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
